package cn.yy.cloudpay;

import java.util.ArrayList;
import java.util.List;

import cn.yy.cloudpay.activity.BaseActivity;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.listener.ITitlebarClickListener;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.ObjectGenerator;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.util.ThirdTransType;
import cn.yy.cloudpay.util.WebserviceRequset;
import cn.yy.cloudpay.view.LoadingDialog;
import cn.yy.cloudpay.view.MyGridAdapter;
import cn.yy.cloudpay.view.MyGridView;
import cn.yy.cloudpay.view.TitlebarLayout;
import cn.yy.cloudpay.view.ToastUtil;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

public class CardPreauthActivity extends BaseActivity {

	private MyGridView gridview;
	private Context mContext;
	private CloudPayApplication mApplication;
	private TitlebarLayout titlebar;
	private RelativeLayout relativeLayout;
	private String businessRstStr;
	private LoadingDialog mProgress;
	private int mOpType;
	private String mSummary; // 以分为单位的金额
	private int mPayType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_card_preauth);
		mContext = this;
		mApplication = (CloudPayApplication) getApplication();
		initView();
	}

	private void initView() {
		mApplication = (CloudPayApplication) getApplication();
		mProgress = new LoadingDialog(mContext, "正在支付，请稍后");
		relativeLayout = (RelativeLayout) findViewById(R.id.include1);
		titlebar = new TitlebarLayout(mContext, relativeLayout, "刷卡预授权");
		titlebar.setTitlebarClickListener(new ITitlebarClickListener() {
			@Override
			public void OnRetrunListener(View view) {
				finish();
			}
		});
		List<String> listItem = new ArrayList<String>();
		List<Integer> listImg = new ArrayList<Integer>();
		if(Constant.BANKPAYTYPE_NONGSHAN.equals(mApplication.getOperator().getBankType())){
			listItem.add("预授权");
			listItem.add("预授权撤销");
			listItem.add("预授权完成请求");
			listItem.add("预授权完成撤销");

			listImg.add(R.drawable.card_preauth);
			listImg.add(R.drawable.card_preauth_cancel);
			listImg.add(R.drawable.card_preauth_fin);
			listImg.add(R.drawable.card_preauth_cancel);
		}else if(Constant.BANKPAYTYPE_YINGSHEN.equals(mApplication.getOperator().getBankType())){
			listItem.add("预授权");
			listItem.add("预授权撤销");
			listItem.add("预授权完成通知");

			listImg.add(R.drawable.card_preauth);
			listImg.add(R.drawable.card_preauth_cancel);
			listImg.add(R.drawable.card_preauth_fin);
		}else{
			Toast.makeText(mContext, "刷卡通道未设置！", Toast.LENGTH_LONG).show();
		}
		String[] img_text = listItem.toArray(new String[listItem.size()]);
		int[] imgs = new int[listImg.size()];
		for(int i=0;i<listImg.size();i++)
		{
			imgs[i] = listImg.get(i);
		}
//		String[] img_text = { "预授权", "预授权撤销", "预授权完成通知"};
//		int[] imgs = { R.drawable.card_preauth, R.drawable.card_preauth_cancel,R.drawable.card_preauth_fin};
		gridview=(MyGridView) findViewById(R.id.gridview);
		gridview.setAdapter(new MyGridAdapter(this,img_text,imgs));
		gridview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
									long arg3) {
				// TODO Auto-generated method stub
				if(Constant.BANKPAYTYPE_NONGSHAN.equals(mApplication.getOperator().getBankType())){
					switch(arg2){
						case 0: // 预授权
							mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
							preauth();
							break;
						case 1: // 预授权撤销
							mOpType = Constant.KEYBOARD_OP_TYPE_RETURN;
							mPayType = Constant.PAY_TYPE_CANCELPREAUTH_NS;
							callPayNS(new Intent(), ThirdTransType.TRANS_VOID_PREAUTH);
//							Intent data = new Intent();
//							data.putExtra("transResult",0);
//							data.putExtra("pan","10101010");
//							data.putExtra("amount",1222l);
//							callPayed(data);
							break;
						case 2: // 预授权完成请求
							mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
							mPayType = Constant.PAY_TYPE_DONEPREAUTH_NS;
							callPayNS(new Intent(), ThirdTransType.TRANS_AUTHSALE);
							break;
						case 3: // 预授权完成撤销
							mOpType = Constant.KEYBOARD_OP_TYPE_RETURN;
							mPayType = Constant.PAY_TYPE_DONECANCELPREAUTH_NS;
							callPayNS(new Intent(),  ThirdTransType.TRANS_VOID_AUTHSALE);
							break;
					}
				}else{
					switch(arg2){
						case 0: // 预授权
							mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
							preauth();
							break;
						case 1: // 预授权撤销
							mOpType = Constant.KEYBOARD_OP_TYPE_RETURN;
							mPayType = Constant.PAY_TYPE_CANCELPREAUTH_YS;
							callPay(new Intent(), 108);
							break;
						case 2: // 预授权完成通知
							mOpType = Constant.KEYBOARD_OP_TYPE_PAY;
							mPayType = Constant.PAY_TYPE_DONEPREAUTH_YS;
							callPay(new Intent(), 103);
							break;
					}
				}

			}
		});
	}

	// 预授权
	public void preauth(){
		showKeyboard(Constant.GREQUEST_CODE_PREAUTH);
	}

	/**
	 * 键盘输入
	 */
	private void showKeyboard(int requestCode) {
		Intent intent = new Intent();
		intent.putExtra(Constant.PARAM_ISRETURN, false);
		intent.setClass(CardPreauthActivity.this, KeyboardActivity.class);
		startActivityForResult(intent, requestCode);
	}

	/**
	 * 返回结果处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case Constant.GREQUEST_CODE_PREAUTH: // 预授权
				if(resultCode == RESULT_OK){
					String amount = data.getStringExtra(Constant.PARAM_SUMMARY);
					Intent intent = new Intent();
					intent.putExtra("amount", Long.parseLong(amount));//金额统一以分为单位,long类型
					mSummary =  amount.toString();
					if(Constant.BANKPAYTYPE_NONGSHAN.equals(mApplication.getOperator().getBankType())){
						mPayType = Constant.PAY_TYPE_PREAUTH_NS;
						callPayNS(intent, ThirdTransType.TRANS_PREAUTH);
					}else if(Constant.BANKPAYTYPE_YINGSHEN.equals(mApplication.getOperator().getBankType())){
						mPayType = Constant.PAY_TYPE_PREAUTH_YS;
						callPay(intent, 104);
					}else{
						Toast.makeText(mContext, "刷卡通道未设置！", Toast.LENGTH_LONG).show();
					}
				}else{

				}
				break;
			case 100104: // 预授权返回结果（银盛）
			case 100108:// 预授权撤销返回结果（银盛）
			case 100103: // 预授权完成通知返回结果（银盛）
				callPayed(data);
				break;
			case 2005:// 预授权返回结果（农商）
			case 2009:// 预授权撤销返回结果（农商）
			case 2003:// 预授权完成请求返回结果（农商）
			case 2008:// 预授权完成撤销返回结果（农商）
				if(data==null){
					break;
				}
				String responseCode = data.getStringExtra("responseCode"); // 交易状态码：00成功；其他失败
				if("00".equals(responseCode)){
					// 保存交易记录
					Long amount = data.getLongExtra("amount", 0l);	// 金额
					String pan	= data.getStringExtra("cardNo");	// 卡号
					String bankCardType	= data.getStringExtra("bankCardType");	//借贷记标识
					mSummary =  amount.toString();
					PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
					task.execute(pan,bankCardType);
				}
				break;
		}
	}

	private void callPay(Intent intent, int transType) {
		intent.setAction("com.ys.smartpos.pay.sdk");
		intent.putExtra("transType", transType);
		startActivityForResult(intent, Integer.valueOf("100" + transType));
	}

	private void callPayed(Intent data){
		int transResult = data.getIntExtra("transResult", -1);
		if(transResult == 0){
			// 保存交易记录
			String pan	= data.getStringExtra("pan");	// 卡号
			Long amount = data.getLongExtra("amount", 0l);	// 金额
			String bankCardType	= data.getStringExtra("bankCardType");	//借贷记标识
			mSummary =  amount.toString();
			PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
			task.execute(pan,bankCardType);
		}
	}

	private void callPayNS(Intent intent, int transType) {
		intent.setClassName("com.newland.nxs", "com.newland.payment.ui.activity.MainActivity");
		intent.putExtra("transType", transType);
		startActivityForResult(intent, Integer.valueOf("200" + transType));
	}

	private void toast(final String msg) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(CardPreauthActivity.this, msg, Toast.LENGTH_SHORT).show();
			}
		});
	}

	// 支付宝或微信支付异步任务
	private class PayAsyncTask extends AsyncTask<String, Void, String> {

		private ObjectGenerator generator = new ObjectGenerator(mContext);

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			String jsonStr = "";
			String rs = "";
			try {
				switch(mOpType){
					case Constant.KEYBOARD_OP_TYPE_PAY: // 支付
						jsonStr = generator.getScanPayReqStr(mPayType,getSummary(), mApplication.getOperator(), params);
						break;
					case Constant.KEYBOARD_OP_TYPE_RETURN: // 退款
						jsonStr = generator.getScanRetundReqStr(mPayType,getSummary(), mApplication.getOperator(),params);
						break;
				}
				rs =	WebserviceRequset.requsetService(jsonStr,mApplication.getServiceAddress());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgress.dismiss();
			//如果支付成功，关闭扫描页面
			JSONObject resultJSON = null;
			Message message = new Message();
			try {
				if("anyType{}".equals(result)){
					message.obj = "返回值anyType{}:获取不到服务器证书文件";
					message.what = Constant.BUSINESS_FAILED;
				}else{
					resultJSON = new JSONObject(result);
					String resultCode = resultJSON.getString("result");
					String returnMsg = resultJSON.getString("return_msg");
					message.obj = returnMsg;
					if(resultCode.equals("SUCCESS")) {
						// 解析result判断订单支付情况，返回MainActivity或者弹框提示
						message.what = Constant.BUSINESS_SUCCESS;//处理打印，调回页面业务

						//20170225 添加支付成功广播
						int money = Integer.parseInt(mSummary);

						Log.e(">>>>result>", result);
						String serialNum = "";
						try{
							JSONObject jsonMsg = new JSONObject(returnMsg);
							serialNum =  jsonMsg.getString("outTradeNo");//流水号
						}catch(Exception e){
							e.printStackTrace();
						}
						if (money > 0) {
							Intent intent=new Intent();
							intent.setAction("cn.yy.pos.launcher.broadcastReceiver.AmountBroadcastReceiver.PAYMENT_SUCCESS");
							intent.putExtra("money", money);
							intent.putExtra("payId", serialNum);
							sendBroadcast(intent);
						}else Log.e(">>>>>>mSummary", "mSummary is null");

					} else {
						message.what = Constant.BUSINESS_FAILED;
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
				message.obj = "数据解析错误:"+result;
				message.what = Constant.BUSINESS_FAILED;
			} finally {
				mHandler.sendMessage(message);
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			businessRstStr = (String) msg.obj; // 扫描到的授权码或支付后返回的消息
			switch (msg.what) {
				case Constant.BUSINESS_SUCCESS :
					ToastUtil.showToast(mContext, "支付成功", ToastUtil.SUCCESS);
					finish();
					break;
				case Constant.BUSINESS_FAILED : // 支付失败

					new AlertDialog.Builder(CardPreauthActivity.this).setTitle("支付失败")
							.setMessage(businessRstStr)
							.setPositiveButton("取消",new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {

								}
							})
							.setPositiveButton("确定",new DialogInterface.OnClickListener() {//添加确定按钮
								@Override
								public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

								}
							}).show();
					break;
				default:
					break;
			}
		}
	};

	private int getSummary(){
		if(StringUtil.isEmpty(mSummary)){
			mSummary = "0";
		}
		return Integer.parseInt(mSummary.trim());
	}


	@Override
	protected void onResume() {
		super.onResume();
	}
}